<!--
  多窗口演示页面
  
  演示多窗口创建、管理和广播通信功能
-->

<template>
  <div class="multi-window-page">
    <div class="multi-window-demo">
      <div class="header">
        <h2>🪟 多窗口广播通信演示</h2>
        <p class="subtitle">创建多个窗口，演示窗口间的实时广播通信</p>
      </div>

      <!-- 窗口管理区域 -->
      <div class="window-management">
        <h3>📋 窗口管理</h3>
        <div class="controls">
          <button @click="createChildWindow" class="btn btn-primary">
            ➕ 创建新窗口
          </button>
          <button @click="refreshWindowList" class="btn btn-secondary">
            🔄 刷新窗口列表
          </button>
          <span class="window-count">
            当前子窗口数量: {{ childWindows.length }}
          </span>
        </div>
        
        <div v-if="childWindows.length > 0" class="window-list">
          <h4>活动窗口列表:</h4>
          <div v-for="window in childWindows" :key="window.id" class="window-item">
            <span class="window-title">{{ window.title }}</span>
            <span class="window-id">ID: {{ window.id }}</span>
          </div>
        </div>
      </div>

      <!-- 广播消息测试区域 -->
      <div class="broadcast-test">
        <h3>📡 广播消息测试</h3>
        <div class="message-form">
          <div class="form-group">
            <select v-model="testMessageType" class="input">
              <option value="chat">💬 聊天消息</option>
              <option value="notification">🔔 通知消息</option>
              <option value="status">📊 状态更新</option>
              <option value="alert">⚠️ 警告消息</option>
            </select>
            <input 
              v-model="testMessageContent" 
              class="input"
              placeholder="输入要广播的消息内容..."
            >
            <button @click="sendTestMessage" class="btn btn-success">
              📢 广播到所有窗口
            </button>
            <button @click="sendSimpleTest" class="btn btn-primary">
              🧪 发送简单测试
            </button>
          </div>
        </div>
      </div>

      <!-- 消息日志区域 -->
      <div class="message-logs">
        <h3>📝 广播消息日志</h3>
        <div class="log-controls">
          <button @click="clearLogs" class="btn btn-warning btn-sm">清空日志</button>
          <span class="log-count">共 {{ broadcastLogs.length }} 条消息</span>
        </div>
        
        <div class="log-list">
          <div v-if="broadcastLogs.length === 0" class="empty-log">
            还没有广播消息记录
          </div>
          <div v-for="(log, index) in broadcastLogs" :key="index" class="log-item">
            <span class="log-time">{{ log.time }}</span>
            <span class="log-type">{{ log.type }}</span>
            <span class="log-sender">{{ log.sender }}</span>
            <span class="log-content">{{ log.content }}</span>
          </div>
        </div>
      </div>

      <!-- 使用说明 -->
      <div class="instructions">
        <h3>📖 使用说明</h3>
        <ol>
          <li><strong>创建子窗口</strong>：点击"创建新窗口"按钮创建子窗口</li>
          <li><strong>验证任务栏显示</strong>：检查Windows任务栏，子窗口应该显示为独立的程序图标</li>
          <li><strong>窗口管理</strong>：
            <ul>
              <li>子窗口可以独立最小化/最大化/关闭</li>
              <li>在任务栏中点击可以切换窗口焦点</li>
              <li>使用"刷新窗口列表"同步窗口状态</li>
            </ul>
          </li>
          <li><strong>广播通信测试</strong>：
            <ul>
              <li>在主窗口发送消息 → 所有子窗口实时接收</li>
              <li>在子窗口发送消息 → 主窗口和其他子窗口接收</li>
            </ul>
          </li>
          <li><strong>多窗口效果</strong>：创建多个子窗口，测试群体广播通信</li>
        </ol>
        <div class="tip">
          💡 <strong>提示</strong>：如果子窗口没有在任务栏显示，请尝试刷新窗口列表或重新创建窗口。
        </div>
      </div>
    </div>

    <!-- 消息提示 -->
    <div v-if="message.text" :class="['message', message.type]">
      {{ message.text }}
    </div>
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted } from 'vue'

// 响应式数据
const childWindows = ref<Array<{ id: string; title: string }>>([])
const broadcastLogs = ref<Array<{ time: string; type: string; content: string; sender: string }>>([])
const message = ref({ text: '', type: 'info' })
const testMessageType = ref('chat')
const testMessageContent = ref('')

/**
 * 创建子窗口
 */
const createChildWindow = async () => {
  try {
    const timestamp = new Date().toLocaleTimeString('zh-CN')
    const result = await window.api.window.createChild({
      title: `子窗口 - ${timestamp}`
    })
    
    if (result.success && result.windowId) {
      childWindows.value.push({
        id: result.windowId,
        title: `子窗口 - ${timestamp}`
      })
      showMessage('子窗口创建成功！现在应该在任务栏中显示', 'success')
    } else {
      showMessage(`创建子窗口失败: ${result.error}`, 'error')
    }
  } catch (error) {
    showMessage(`创建子窗口出错: ${error}`, 'error')
  }
}

/**
 * 发送测试消息
 */
const sendTestMessage = () => {
  if (!testMessageContent.value.trim()) {
    showMessage('请输入消息内容', 'warning')
    return
  }

  const messageData = {
    type: testMessageType.value,
    content: testMessageContent.value,
    sender: 'main-window',
    timestamp: new Date().toISOString()
  }

  console.log(`[主窗口] 发送广播消息 - 类型: ${testMessageType.value}`)
  console.log(`[主窗口] 消息数据:`, messageData)

  window.api.broadcast.send(testMessageType.value, messageData)
  
  // 添加到日志
  broadcastLogs.value.unshift({
    time: new Date().toLocaleTimeString(),
    type: testMessageType.value,
    content: testMessageContent.value,
    sender: 'main-window'
  })
  
  showMessage(`已广播${testMessageType.value}消息`, 'success')
  testMessageContent.value = ''
}

/**
 * 发送简单测试消息
 */
const sendSimpleTest = () => {
  console.log('[主窗口] 🧪 开始发送简单测试消息')
  
  const simpleMessage = {
    content: '这是一条简单的测试消息',
    sender: 'main-window',
    timestamp: new Date().toISOString(),
    type: 'chat'
  }
  
  console.log('[主窗口] 📤 发送简单消息:', simpleMessage)
  
  try {
    window.api.broadcast.send('chat', simpleMessage)
    console.log('[主窗口] ✅ 简单消息发送成功')
    showMessage('简单测试消息已发送', 'success')
  } catch (error) {
    console.error('[主窗口] ❌ 简单消息发送失败:', error)
    showMessage('简单测试消息发送失败', 'error')
  }
}

/**
 * 清空日志
 */
const clearLogs = () => {
  broadcastLogs.value = []
  showMessage('日志已清空', 'info')
}

/**
 * 刷新窗口列表
 */
const refreshWindowList = async () => {
  try {
    const windows = await window.api.window.getList()
    // 过滤出子窗口（排除主窗口）
    const childWindowList = windows.filter(w => w.title.includes('子窗口'))
    
    // 更新本地窗口列表
    childWindows.value = childWindowList.map(w => ({
      id: w.id.toString(),
      title: w.title
    }))
    
    showMessage(`发现 ${childWindowList.length} 个子窗口`, 'info')
  } catch (error) {
    showMessage(`刷新窗口列表失败: ${error}`, 'error')
  }
}

/**
 * 显示消息
 */
const showMessage = (text: string, type: string = 'info') => {
  message.value = { text, type }
  setTimeout(() => {
    if (message.value.text === text) {
      message.value.text = ''
    }
  }, 3000)
}

// 生命周期
onMounted(() => {
  // 监听子窗口关闭事件
  window.api.window.onChildClosed((data) => {
    const index = childWindows.value.findIndex(w => w.id === data.windowId)
    if (index !== -1) {
      const window = childWindows.value[index]
      childWindows.value.splice(index, 1)
      showMessage(`子窗口 ${window.title} 已关闭`, 'info')
    }
  })
  
  // 监听广播消息
  console.log('[主窗口] 开始设置广播消息监听器')
  const messageTypes = ['chat', 'notification', 'status', 'alert', 'quick-message', 'child-window-ready']
  
  messageTypes.forEach(type => {
    console.log(`[主窗口] 🎧 设置监听器: ${type}`)
    window.api.broadcast.on(type, (data) => {
      console.log(`[主窗口] 📨 收到广播消息 - 类型: ${type}, 发送者: ${data?.sender || 'unknown'}`)
      console.log(`[主窗口] 📨 消息内容:`, data)
      
      if (data?.sender !== 'main-window') {
        broadcastLogs.value.unshift({
          time: new Date().toLocaleTimeString(),
          type: data?.type || type,
          content: data?.content || JSON.stringify(data),
          sender: data?.sender || 'unknown'
        })
        
        // 只保留最近30条日志
        if (broadcastLogs.value.length > 30) {
          broadcastLogs.value.pop()
        }
        
        // 特殊处理子窗口准备就绪消息
        if (type === 'child-window-ready') {
          console.log('[主窗口] ✅ 收到子窗口准备就绪消息，发送自动回复')
          showMessage('子窗口已连接！', 'success')
          
          // 自动回复一条消息测试双向通信
          setTimeout(() => {
            const testResponse = {
              content: '主窗口收到了你的准备就绪消息！这是一条自动回复。',
              sender: 'main-window',
              timestamp: new Date().toISOString(),
              type: 'chat'
            }
            console.log('[主窗口] 🚀 发送自动回复消息:', testResponse)
            window.api.broadcast.send('chat', testResponse)
          }, 1000)
        }
      }
    })
  })
  
  console.log('[主窗口] 广播监听器设置完成')
})

onUnmounted(() => {
  // 清理广播监听器
  const messageTypes = ['chat', 'notification', 'status', 'alert', 'quick-message', 'child-window-ready']
  messageTypes.forEach(type => {
    window.api.broadcast.off(type)
  })
})
</script>

<style scoped>
.multi-window-page {
  min-height: 100vh;
  overflow: auto;
  box-sizing: border-box;
}

.multi-window-demo {
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  font-family: -apple-system, BlinkMacSystemFont, 'Segoe UI', Roboto, sans-serif;
}

.multi-window-demo .header {
  text-align: center;
  margin-bottom: 40px;
}

.multi-window-demo .header h2 {
  color: var(--text-primary, #2c3e50);
  margin: 0;
  font-size: 2.2em;
}

.multi-window-demo .subtitle {
  color: var(--text-secondary, #7f8c8d);
  margin: 5px 0 0 0;
  font-size: 1.1em;
}

.window-management, .broadcast-test, .message-logs, .instructions {
  background: var(--card-bg, #f8f9fa);
  border-radius: 12px;
  padding: 25px;
  margin-bottom: 30px;
  border-left: 4px solid var(--primary-color, #3498db);
  box-shadow: var(--shadow-sm, 0 2px 10px rgba(0, 0, 0, 0.1));
  border: 1px solid var(--card-border, transparent);
}

.window-management h3, .broadcast-test h3, .message-logs h3, .instructions h3 {
  margin: 0 0 20px 0;
  color: var(--text-primary, #2c3e50);
  font-size: 1.3em;
}

.controls {
  display: flex;
  gap: 20px;
  align-items: center;
  flex-wrap: wrap;
  margin-bottom: 20px;
}

.window-count {
  background: var(--primary-light, #e3f2fd);
  color: var(--primary-color, #1976d2);
  padding: 8px 16px;
  border-radius: 20px;
  font-weight: 600;
  font-size: 14px;
}

.window-list {
  background: white;
  border-radius: 8px;
  padding: 20px;
  border: 1px solid #dee2e6;
}

.window-list h4 {
  margin: 0 0 15px 0;
  color: #495057;
}

.window-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  margin: 8px 0;
  background: var(--bg-secondary, #f8f9fa);
  border-radius: 6px;
  border-left: 3px solid var(--success-color, #28a745);
}

.window-title {
  font-weight: 600;
  color: var(--text-primary, #2c3e50);
}

.window-id {
  font-size: 12px;
  color: var(--text-muted, #6c757d);
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
}

.message-form {
  background: white;
  padding: 20px;
  border-radius: 8px;
  border: 1px solid #dee2e6;
}

.form-group {
  display: flex;
  gap: 15px;
  align-items: center;
  flex-wrap: wrap;
}

.form-group .input {
  padding: 10px 15px;
  border: 2px solid #bdc3c7;
  border-radius: 6px;
  font-size: 14px;
  min-width: 150px;
}

.form-group .input:focus {
  outline: none;
  border-color: #3498db;
}

.btn {
  padding: 10px 20px;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  font-weight: 500;
  transition: all 0.3s ease;
  min-width: 120px;
}

.btn:hover {
  transform: translateY(-2px);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

.btn-primary {
  background: linear-gradient(45deg, var(--primary-color, #3498db), var(--primary-hover, #2980b9));
  color: var(--text-inverse, white);
  border: 1px solid var(--primary-color, transparent);
}

.btn-secondary {
  background: linear-gradient(45deg, var(--text-secondary, #757575), #616161);
  color: var(--text-inverse, white);
  border: 1px solid var(--text-secondary, transparent);
}

.btn-success {
  background: linear-gradient(45deg, var(--success-color, #2ecc71), var(--success-hover, #27ae60));
  color: var(--text-inverse, white);
  border: 1px solid var(--success-color, transparent);
}

.btn-warning {
  background: linear-gradient(45deg, var(--warning-color, #f39c12), var(--warning-hover, #e67e22));
  color: var(--text-inverse, white);
  border: 1px solid var(--warning-color, transparent);
}

.btn-sm {
  padding: 6px 12px;
  font-size: 12px;
  min-width: 80px;
}

.log-controls {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.log-count {
  color: #6c757d;
  font-size: 14px;
}

.log-list {
  background: #2c3e50;
  color: white;
  border-radius: 8px;
  padding: 15px;
  max-height: 300px;
  overflow-y: auto;
}

.empty-log {
  text-align: center;
  color: #95a5a6;
  font-style: italic;
  padding: 20px;
}

.log-item {
  display: flex;
  gap: 15px;
  padding: 8px;
  margin: 5px 0;
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
  font-family: 'Monaco', 'Menlo', 'Ubuntu Mono', monospace;
  font-size: 12px;
}

.log-time {
  color: #95a5a6;
  min-width: 80px;
}

.log-type {
  color: #3498db;
  font-weight: 600;
  min-width: 80px;
}

.log-sender {
  color: #f39c12;
  font-weight: 600;
  min-width: 100px;
}

.log-content {
  color: #ecf0f1;
  flex: 1;
}

.instructions ol {
  color: #495057;
  line-height: 1.6;
}

.instructions li {
  margin: 8px 0;
  padding-left: 10px;
}

.instructions ul {
  margin: 5px 0 10px 0;
  padding-left: 20px;
}

.instructions ul li {
  margin: 4px 0;
  list-style-type: disc;
}

.tip {
  background: #e8f5e8;
  border: 1px solid #4caf50;
  border-radius: 6px;
  padding: 15px;
  margin-top: 20px;
  color: #2e7d32;
  font-size: 14px;
}

.message {
  padding: 12px 20px;
  border-radius: 6px;
  margin: 20px;
  font-weight: 500;
  border-left: 4px solid;
  position: fixed;
  top: 20px;
  right: 20px;
  z-index: 1000;
  min-width: 300px;
  animation: slideIn 0.3s ease;
}

.message.info {
  background: #d1ecf1;
  color: #0c5460;
  border-color: #17a2b8;
}

.message.success {
  background: #d4edda;
  color: #155724;
  border-color: #28a745;
}

.message.warning {
  background: #fff3cd;
  color: #856404;
  border-color: #ffc107;
}

.message.error {
  background: #f8d7da;
  color: #721c24;
  border-color: #dc3545;
}

@keyframes slideIn {
  from {
    transform: translateX(100%);
    opacity: 0;
  }
  to {
    transform: translateX(0);
    opacity: 1;
  }
}

/* 滚动条样式 */
.log-list::-webkit-scrollbar {
  width: 8px;
}

.log-list::-webkit-scrollbar-track {
  background: rgba(255, 255, 255, 0.1);
  border-radius: 4px;
}

.log-list::-webkit-scrollbar-thumb {
  background: rgba(255, 255, 255, 0.3);
  border-radius: 4px;
}

.log-list::-webkit-scrollbar-thumb:hover {
  background: rgba(255, 255, 255, 0.5);
}

/* 响应式设计 */
@media (max-width: 768px) {
  .multi-window-demo {
    padding: 15px;
  }
  
  .controls {
    flex-direction: column;
    align-items: stretch;
  }
  
  .form-group {
    flex-direction: column;
  }
  
  .form-group .input {
    min-width: auto;
  }
}
</style>
